package com.alorm.core.sqlgen;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import com.alorm.core.exceptions.AlormException;
import com.alorm.utils.AlormUtils;
import com.test.bo.Etudiant;

public class SqlStatementsGenerator {

	private boolean cascade = false;

	public String getDeleteStatement(Object pObject) {
		StringBuilder strb = new StringBuilder();

		if (!cascade) {
			Class lClass = pObject.getClass();
			Method method = null;
			String tableName = AlormUtils.getClassName(lClass);
			String pkName = AlormUtils.getPkName(lClass);
			String getterMethod = AlormUtils.getGetterMethod(pkName);
			Number number = null;
			try {

				method = lClass.getMethod(getterMethod);
				number = (Number) method.invoke(pObject);

			} catch (Exception e) {
				throw new AlormException("an error has occured due to : ", e);
			}

			strb.append("delete from ");
			strb.append(tableName);
			strb.append(" where ");
			strb.append(pkName);
			strb.append("=");
			strb.append(String.valueOf(number));
		}

		return strb.toString();

	}

	public String getUpdateStatement(Object pObject) {
		StringBuilder strb = new StringBuilder("update ");
		Class lClass = pObject.getClass();
		String[] fieldsName = AlormUtils.getAllFieldsName(lClass);
		Map<String, String> map = null;
		String tableName = AlormUtils.getClassName(lClass);
		Method method = null;
		String pkName = AlormUtils.getPkName(lClass);
		String getterMethod = AlormUtils.getGetterMethod(pkName);
		Number number = null;
		try {
			map = AlormUtils.getAllFieldsValue(pObject);
			method = lClass.getMethod(getterMethod);
			number = (Number) method.invoke(pObject);
		} catch (Exception e) {

			throw new AlormException("An error occured :", e);
		}

		strb.append(tableName);
		strb.append(" SET ");

		for (Map.Entry<String, String> entry : map.entrySet()) {

			strb.append(entry.getKey() + "=" + entry.getValue() + "  , ");

		}

		strb.deleteCharAt(strb.length() - 2);
		strb.append(" where ");
		strb.append(pkName);
		strb.append("=");
		strb.append(String.valueOf(number));
		return strb.toString();
	}
//
//	public static void main(String[] args) {
//
//		SqlStatementsGenerator sql = new SqlStatementsGenerator();
//		Etudiant e = new Etudiant(1, "taz", "baz");
//		Etudiant e2 = new Etudiant(1, "ez", "eo");
//
//		System.out.println(sql.getUpdateStatement(e));
//
//	}

	public boolean isCascade() {
		return cascade;
	}

	public void setCascade(boolean cascade) {
		this.cascade = cascade;
	}

}
